package cn.rsa.aiwangren.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * RSA
 *
 * @author xiangtianlei
 * @date 2024/04/09
 */
public class RSAUtil {
    private static final Logger log = LoggerFactory.getLogger(RSAUtil.class);

    /**
     * encryption algorithm RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * encryption
     *
     * @param data      data
     * @param publicKey publicKey
     * @return byte
     * @throws Exception Exception
     */
    public static byte[] encrypt(byte[] data, String publicKey, int MAX_ENCRYPT_BLOCK) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        byte[] keyBytes = Base64Util.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        return doFinal(data, cipher, MAX_ENCRYPT_BLOCK);
    }

    /**
     * Decrypt
     *
     * @param text       text
     * @param privateKey privateKey
     * @return byte
     * @throws Exception Exception
     */
    public static byte[] decrypt(byte[] text, String privateKey, int MAX_DECRYPT_BLOCK) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        byte[] keyBytes = Base64Util.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        return doFinal(text, cipher, MAX_DECRYPT_BLOCK);
    }

    /**
     * 对数据进行加解密
     *
     * @param data   数据
     * @param cipher Cipher 对象
     * @param maxLen 最大分段长度
     * @return byte[]
     * @throws Exception Exception
     */
    private static byte[] doFinal(byte[] data, Cipher cipher, int maxLen) throws Exception {
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 分段加解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > maxLen) {
                cache = cipher.doFinal(data, offSet, maxLen);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * maxLen;
        }
        byte[] result = out.toByteArray();
        out.close();
        return result;
    }
}
